package com.max.common.oauth.oauth20;

import java.util.HashMap;
import java.util.Map;

import com.max.common.util.HttpTool;
import com.max.common.util.StringUtil;
import com.max.common.util.HttpTool.Response;

public class Oauth20 
{

	public static String authorize(String clientName, String response_type) 
	{
		String authorizeURL = null;
		
		if(!StringUtil.isEmpty(clientName))
		{
			Client client = Config.getClientMap().get(clientName);
			
			StringBuffer sb = new StringBuffer();
			sb.append(client.getAuthorization().getAuthorizeURL())
			  .append("?client_id=").append(client.getClient_id())
			  .append("&redirect_uri=").append(client.getRedirect_uri())
			  .append("&response_type=").append(response_type);
			
			authorizeURL = sb.toString();
		}
		
		return authorizeURL;
	}
	
	
	public static AccessToken getAccessTokenByCode(String clientName, String code) throws Exception 
	{
		AccessToken accessToken = null;
		
		if(!StringUtil.isEmpty(clientName))
		{
			Client client = Config.getClientMap().get(clientName);
			
			Map<String,String> bodyParams = new HashMap<String,String>();
			bodyParams.put("client_id", client.getClient_id());
			bodyParams.put("client_secret", client.getClient_secret());
			bodyParams.put("grant_type", client.getGrant_type());
			bodyParams.put("code", code);
			bodyParams.put("redirect_uri", client.getRedirect_uri());
			
			HttpTool httpTool = new HttpTool();
			Response res = httpTool.request(client.getAuthorization().getMethod(), 
					client.getAuthorization().getAccessTokenURL(), bodyParams);
			
			accessToken = new AccessToken(res);
		}
		
		return accessToken;
	}
}
